import cluster from 'cluster';
import * as os from 'os';
import { Injectable } from '@nestjs/common';

// const cluster = require('cluster');

const isCluster = process.argv[3] || 1;
const numCPUs = os.cpus().length;

@Injectable()
export class AppClusterService {
  // eslint-disable-next-line @typescript-eslint/ban-types
  static clusterize(callback: Function): void {
    if (isCluster === 1) {
      if (cluster.isMaster) {
        console.log(`Master server started on ${process.pid}`);
        for (let i = 0; i < numCPUs; i++) {
          cluster.fork();
        }
        cluster.on('exit', (worker, code, signal) => {
          console.log(`Worker ${worker.process.pid} died. Restarting`);
          console.log(`code: ${code}, signal: ${signal}`);
          cluster.fork();
        });
      } else {
        console.log(`Cluster server started on ${process.pid}`);
        callback();
      }
    } else {
      console.log(`Cluster server started on ${process.pid}`);
      callback();
    }
  }
}
